package com.lb.bs.client.adapter.proxy.cglib;

import com.lb.bs.client.adapter.cache.LBCache;
import com.lb.bs.client.annotation.LBItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * program: LB-BS-Client
 * author: bsworld.xie
 * create: 2020-04-17 18:03
 * description:
 */
public class LbInterceptor implements MethodInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LbInterceptor.class);

    private Object originBean;

    public LbInterceptor(Object originBean) {
        this.originBean = originBean;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object result = null;
        String methodName = null;
        try {
            LBItem lbItemAnno = method.getDeclaredAnnotation(LBItem.class);
            if (lbItemAnno == null) {
                result = methodProxy.invokeSuper(o, objects);
                return result;
            }
            Object cacheVal = LBCache.getCacheVal(method.getDeclaringClass(), lbItemAnno);
            if (cacheVal != null) {
                return cacheVal;
            }
            if (cacheVal == null) {
                try {
                    //增加最后一层属性缓存
                    methodName = method.getName();
                    Method originMethod = originBean.getClass().getDeclaredMethod(methodName);
                    if (originMethod != null) {
                        result = originMethod.invoke(originBean, objects);
                    }
                } catch (Throwable e) {
                    logger.error("LbInterceptor.class,methodName:{}, e:", methodName, e);
                }
                return result;
            }

        } finally {

        }
        return result;

    }
}
